<template>
	<view>
		<u-swiper :list="banner" keyName="img_url" showTitle :autoplay="true" indicatorMode="line" circular></u-swiper>
		<u-sticky bgColor="#fff">
			<view style="display: flex;justify-content: center;">
				<u-tabs :list="sortList" is-scroll="false" @change="sort"></u-tabs>
			</view>
		</u-sticky>
		<u-row class="u-p-l-8 u-p-r-8">
			<u-col span="6" v-for="(item,index) in goods" :key="index">
				<goodsCard :item="item"></goodsCard>
			</u-col>
		</u-row>
	</view>
</template>

<script>
	let _this;
	export default {
		data() {
			return {
				loading: true,
				page: 1, //首页数据请求页码
				current: 0, //首页sort索引值
				banner: [], //顶部banner
				goods: [], //商品列表
				sortList: [{
						name: '默认'
					},
					{
						name: '销量'
					},
					{
						name: '推荐'
					},
					{
						name: '最新'
					}
				]
			}
		},
		async onLoad() {
			_this = this;
			this.getData();
			const currentPage = getCurrentPages().pop();	 //获取当前页面信息
			const {options,route} = currentPage; //解构对象内容
			console.log(options);
			const optionsKeys = Object.keys(options); //将options中的key获取，以数组的形式返回
			let params = '';
			if(optionsKeys.length != 0){
				//说明当前页面有参数，则需要用?属性=值的方式将相关内容拼接到route中去
				params = optionsKeys.reduce((pre,current)=>{
					if(current.length > 0){
						return pre + current + '=' + options[current] + '&';
					}
					else{
						return pre;
					}
				},"?").slice(0,-1);
			}
		},
		methods: {
			sort: (e) => {
				_this.current = e.index;
				//重新分类时，要把页面清空，要把商品列表清空
				_this.page = 1;
				_this.goods = [];
				_this.getData();
			},
			async getData() {
				/* let res = await uni.$u.http.get('/api/user',{header:{Authorization:'bearer '}});
				console.log(res);
				return; */
				try {
					//配置参数
					let params = {
						page: _this.page
					};
					//接下来设置sort参数
					if (_this.current == 1) {
						params.sales = 1
					};
					if (_this.current == 2) {
						params.recommend = 1
					};
					if (_this.current == 3) {
						params.new = 1
					};
					_this.loading = true;
					let res = await uni.$u.http.get('/api/index', {
						params: params
					});
					console.log(res);
					_this.loading = false;
					_this.banner = res.slides;
					//_this.goods = res.goods.data;
					//_this.goods = _this.goods.concat(res.goods.data);
					//console.log(res);
					//if(Object.keys(_this.goods[0]).length == 0){
						//初始化时，为了使用骨架，用了几个空对象，正式内容请求以以后，需要删除这些空对象
						//_this.goods = [];
					//}
					_this.goods = [..._this.goods, ...res.goods.data]
				} catch (res) {
					uni.$u.toast(res.data.message)
				}
			}
		},
		onReachBottom() {
			this.page++;
			this.getData();
		}
	}
</script>

<style lang="scss">
	.u-row{flex-wrap: wrap;}
</style>
